package com.example.demo.dao;

import com.example.demo.model.Product;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ProductDao {

    // 查询所有产品
    @Select("SELECT * FROM product")
    List<Product> findAll();

    // 根据ID查询产品
    @Select("SELECT * FROM product WHERE id = #{id}")
    Product findById(Long id);

    // 插入产品
    @Insert("INSERT INTO product(name, description, price, stock, category) " +
            "VALUES(#{name}, #{description}, #{price}, #{stock}, #{category})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Product product);

    // 更新产品信息
    @Update("UPDATE product SET name=#{name}, description=#{description}, " +
            "price=#{price}, stock=#{stock}, category=#{category} WHERE id=#{id}")
    int update(Product product);

    // 删除产品
    @Delete("DELETE FROM product WHERE id = #{id}")
    int delete(Long id);

    // 根据产品名称模糊查询
    @Select("SELECT * FROM product WHERE name LIKE CONCAT('%', #{name}, '%')")
    List<Product> findByName(String name);

    // 根据分类查询产品
    @Select("SELECT * FROM product WHERE category = #{category}")
    List<Product> findByCategory(String category);

    // 检查产品名称是否存在（排除当前产品）
    @Select("SELECT COUNT(*) FROM product WHERE name = #{name} AND id != #{id}")
    int countByNameExcludeId(@Param("name") String name, @Param("id") Long id);

    // 更新产品库存
    @Update("UPDATE product SET stock = #{stock} WHERE id = #{id}")
    int updateStock(@Param("id") Long id, @Param("stock") Integer stock);

    // 根据价格范围查询产品
    @Select("SELECT * FROM product WHERE price BETWEEN #{minPrice} AND #{maxPrice}")
    List<Product> findByPriceRange(@Param("minPrice") Double minPrice, @Param("maxPrice") Double maxPrice);

    // 查询库存不足的产品
    @Select("SELECT * FROM product WHERE stock < #{minStock}")
    List<Product> findLowStockProducts(@Param("minStock") Integer minStock);
}